﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace VPSDownloader.NET.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DownloadController : ControllerBase
    {
        private readonly ILogger<DownloadController> _logger;

        public DownloadController(ILogger<DownloadController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 通过HttpClient获取另外站点的文件流，再输出
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                _logger.LogTrace("下载地址为空！");
                return Content("请在链接后跟上下载地址后再次访问");
            }

            try
            {
                //解决 CentOS7 Https 下载地址出错的问题;
                var httpClientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
                };

                using HttpClient client = new HttpClient(httpClientHandler);
                var stream = await client.GetStreamAsync(url);
                return File(
                    stream,
                    "application/octet-stream", //二进制流
                    Path.GetFileName(url));
            }
            catch (Exception ex)
            {
                return Content($"出错了：{ex}");
            }
        }
    }
}
